const generateFile = require('../utils/generateFile ');

const renderEntryFile = (conf) => {
    console.log('--cur render server entry config --', conf);
    return new Promise(async (resolve, reject) => {
        const tempFileContent = createContentTemp(conf);
        const { code } = await generateFile(`dist/server.js`, tempFileContent);
        if(code === 1) resolve({ code: 1, data: 'render server.js successfully !'})
        else reject({ code : -1, data: 'render server.js error !'});
    })
}

const createContentTemp = (conf) => {
    if(!conf) return new Error('no conf input createContentTemp error !') ;
    const { port, cors, root, prefix } = conf;
    return  `const express = require('express');
        const bodyParser = require('body-parser');
        // import router
        const entity = require('./route/entity')
        const association = require('./route/association')
        
        const server = express();
        
        server.use(bodyParser.urlencoded({ extended: false }));
        server.use(bodyParser.json())
        server.use(express.static(__dirname));

        server.use(async (req, res, next) => {
            // cors
            res.header("Access-Control-Allow-Origin", "${cors}");
            next();
        });
        
        // load outer router
        server.use('/ent', entity);
        server.use('/ass', association);
        
        server.use('/test', (req, res) => { res.send('test successfully ...'); })
        
        // listen port
        server.listen(${port});`
}

module.exports = renderEntryFile;